package com.sportizz.sport;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.blundell.test.util.Developer_key;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.sportizz.model.ImageLoader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Youtube_list extends BaseAdapter {

	private static final int REQ_START_STANDALONE_PLAYER = 1;
	private static final int REQ_RESOLVE_SERVICE_MISSING = 2;

	Context context;
	Activity act_con;
	ArrayList<String> entityList;
	ArrayList<String> playerlist;
	ProgressDialog pd;
	// com.sportizz.model.ImageLoader imgLoader;
	ImageLoader imgLoader;

	public Youtube_list(Context applicationContext,
			ArrayList<String> entityList, ArrayList<String> playerlist) {

		this.context = applicationContext;
		this.entityList = entityList;
		this.playerlist = playerlist;
		this.act_con = (Activity) applicationContext;
		imgLoader = new ImageLoader(context.getApplicationContext());
	}

	@Override
	public int getCount() {
		return entityList.size();
	}

	@Override
	public Object getItem(int arg0) {
		return getCount();
	}

	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return super.getViewTypeCount();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("DefaultLocale")
	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {

		final LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final ViewHolder holder;

		if (convertView == null) {

			convertView = inflater.inflate(R.layout.video_layout, null);

			holder = new ViewHolder();

			holder.linearlayout = (LinearLayout) convertView
					.findViewById(R.id.hori_video);
			holder.Hori_scroll = (HorizontalScrollView) convertView
					.findViewById(R.id.horizontalScrollView_video);
			holder.title_txt = (TextView) convertView
					.findViewById(R.id.textView_head);
			holder.progress_video = (ProgressBar) convertView
					.findViewById(R.id.progressBar_video);

			holder.progress_video.setVisibility(View.VISIBLE);

			// holder.linearlayout.addView(holder.progress_video);

			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					holder.progress_video.setVisibility(View.VISIBLE);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e2) {
						e2.printStackTrace();
					}

					act_con.runOnUiThread(new Runnable() {

						@Override
						public void run() {

							String[] play_list = playerlist.get(position)
									.split("=");
							Log.d("suraj_", "play_list[1] = " + play_list[1]);

							try {
								String _response = Utils.readJsonFeed(
										"https://gdata.youtube.com/feeds/api/playlists/"
												+ play_list[1]
												+ "?v=2&alt=jsonc", context);

								JSONObject json = new JSONObject(_response);

								JSONArray jsonArray1 = json.getJSONObject(
										"data").getJSONArray("items");

								JSONObject video_array = null;
								Log.d("suraj_", "jsonArray1.length() = "
										+ jsonArray1.length());

								holder.progress_video.setVisibility(View.GONE);
								holder.linearlayout.removeAllViews();

								int ll;
								if (jsonArray1.length() > 10) {
									ll = 10;
								} else {
									ll = jsonArray1.length();
								}

								for (int i = 0; i < ll; i++) {

									JSONObject jsonObject1 = jsonArray1
											.getJSONObject(i);

									String title1 = jsonObject1.getJSONObject(
											"video").getString("title");
									// title.add(title1);
									//
									if(!title1.equals("Deleted video"))
									{
										
									String video_id = jsonObject1
											.getJSONObject("video").getString(
													"id");
									// msg.add(url);
									//
									String thumbUrl = jsonObject1
											.getJSONObject("video")
											.getJSONObject("thumbnail")
											.getString("sqDefault");
									// thumb.add(thumbUrl);

									View additionView = inflater.inflate(
											R.layout.video_row, null, false);

									final LinearLayout linear = (LinearLayout) additionView
											.findViewById(R.id.video_lin_row);

									additionView.setTag(video_id);

									ImageView video_thumb = (ImageView) additionView
											.findViewById(R.id.imageView_video_thumb);
									TextView video_title_thumb = (TextView) additionView
											.findViewById(R.id.txt_video_title);

									video_title_thumb.setText(title1);

									Log.d("suraj_", "VideoTitle = " + thumbUrl);

									 int loader = R.drawable.videos;

									 imgLoader.DisplayImage(thumbUrl,loader,
									 video_thumb);

									holder.linearlayout.addView(linear);

									
									
									
									linear.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {

													// TODO Auto-generated method stub
													Intent data = new Intent(
															act_con,
															Sample_Act_youtube.class);
													data.putExtra(
															"video_id",
															linear.getTag()
																	.toString());
													act_con.startActivity(data);
													
										}

									});
								}
								}

							} catch (Exception e1) {
								e1.printStackTrace();
							}

						}
					});

				}
			});

			t.start();

			convertView.setTag(holder);

		} else {

			holder = (ViewHolder) convertView.getTag();

		}

		Typeface tweet_font = Typeface.createFromAsset(context.getAssets(),
				"hel57.ttf");

		// gone.setVisibility(View.GONE);
		holder.title_txt.setText(entityList.get(position).toUpperCase());
		holder.title_txt.setTypeface(tweet_font);
		holder.title_txt.setGravity(Gravity.CENTER_VERTICAL);

		return convertView;

	}

	static class ViewHolder {
		LinearLayout linearlayout;
		HorizontalScrollView Hori_scroll;
		TextView title_txt;
		ProgressBar progress_video;
	}

	private class imageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView imageView = null;

		imageTask(ImageView iv) {
			this.imageView = iv;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			try {
				return download_Image(params[0]);

			} catch (OutOfMemoryError e) {
				return null;
			}

		}

		@Override
		protected void onPostExecute(Bitmap result) {
			Bitmap output;
			Canvas canvas;
			float roundPx;

			if (result == null) {

				InputStream is = null;
				try {

					result = BitmapFactory.decodeStream(is);

				} catch (Exception e) {
					result = BitmapFactory.decodeResource(
							context.getResources(), R.drawable.tweets);
				}

				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 4f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);
				imageView.setScaleType(ScaleType.FIT_CENTER);

			} else {
				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 4f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);

			}
			super.onPostExecute(result);
		}

	}

	private Bitmap download_Image(String imageUrl) {
		Bitmap myBitmap = null;

		try {
			URL url = new URL(imageUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			myBitmap = BitmapFactory.decodeStream(input);
		} catch (Exception e) {
			InputStream iss = null;
			try {
				iss = context.getResources().getAssets()
						.open("main_menu/videos.png");
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			return BitmapFactory.decodeStream(iss);
		}
		return myBitmap;
	}
}